package com.example.b_308.medical.model.base;


import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.b_308.medical.comment.MedicalContent;
import com.example.b_308.medical.comment.MedicalResult;
import com.example.b_308.medical.comment.net.INetCallBack;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;


import org.apache.http.entity.StringEntity;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * Created by tongkang on 2017/10/31.
 * 模块基类
 */


public abstract class BaseModel<T extends BaseModel> implements Serializable {

    String URL = "http://10.5.10.201:8080";
    /**
     * 网络请求
     */
    private HttpUtils http = new HttpUtils();
    /**
     * 属性列表
     */
    protected Map attrs;

    public BaseModel() {
        http.configCurrentHttpCacheExpiry(0);
        attrs = new HashMap();
    }

    public BaseModel(String json) {
        http.configCurrentHttpCacheExpiry(0);
        try {
            attrs = JSON.parseObject(json, Map.class);
        }catch (Exception e){
            Log.d("BaseModel","json格式不正确");
        }

    }

    public BaseModel(BaseModel baseModel) {
        http.configCurrentHttpCacheExpiry(0);
        putAttrs(baseModel);
    }

    /**
     * get方式获取数据
     *
     * @param url          网络地址
     * @param iNetCallBack 网络回调接口
     */
    public <T extends BaseModel> void getRequestHttp(String url, T t, final INetCallBack iNetCallBack) {
        http.send(HttpRequest.HttpMethod.GET,
              paraseUrl(url, t), new RequestCallBack<Object>() {
                    @Override
                    public void onSuccess(ResponseInfo<Object> responseInfo) {
                        MedicalResult medicalResult = new MedicalResult(responseInfo.result.toString());
                        iNetCallBack.onNetCallBack(medicalResult);
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        iNetCallBack.onNetCallBack(
                                new MedicalResult(MedicalContent.FAIL_CODE, MedicalContent.FAIL_REQUEST));
                    }
                });
    }

    protected <T extends BaseModel> String
    paraseUrl(String url, T t) {
        StringBuilder sb = new StringBuilder();
        sb.append(URL);
        sb.append(url);
        if (null != t) {
            Map<String, Object> map = t.getAttrs();
            if(null!=t&&0!=map.size()){
                sb.append("?");
                for (Map.Entry<String, Object> e: map.entrySet()){
                    sb.append(e.getKey());
                    sb.append("=");
                    sb.append(e.getValue());
                    sb.append("&");
                }
             return    sb.substring(0,sb.lastIndexOf("&"));
            }
        }


        return sb.toString();
    }


    /**
     * post方式提交数据
     *
     * @param url 网络地址
     */
    public <T extends BaseModel> void postData(String url, T t, final INetCallBack iNetCallBack) {
      try {
          http.send(HttpRequest.HttpMethod.POST,URL+url,paraseObjToParams(t), new RequestCallBack<String>() {
              @Override
              public void onSuccess(ResponseInfo<String> responseInfo) {
                  MedicalResult medicalResult = new MedicalResult(responseInfo.result.toString());
                  iNetCallBack.onNetCallBack(medicalResult);
              }

              @Override
              public void onFailure(HttpException error, String msg) {
                  iNetCallBack.onNetCallBack(
                          new MedicalResult(MedicalContent.FAIL_CODE, MedicalContent.FAIL_REQUEST));

              }
          });
      }catch (Exception e){
          Log.d(url,"解析对象json失败");
          e.printStackTrace();

    }

    }

    private <T extends BaseModel> RequestParams paraseObjToParams(T t) {
        RequestParams params = new RequestParams("UTF_8");
        Map map = t.getAttrs();
        params.addHeader("Content-Type", "application/json");
        JSONObject jsonObject = new JSONObject(map);
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toJSONString()));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return params;
    }

    public BaseModel(Map attrs) {
        this.attrs = attrs;
    }

    public void setAttrs(Map attrs) {
        this.put("attrs", attrs);
        this.attrs = attrs;
    }

    /**
     * 获取属性
     *
     * @param key
     * @return
     */
    public Object get(String key) {
        return attrs.get(key);
    }

    public void put(String key, Object value) {
        attrs.put(key, value);
    }

    public void putAttrs(BaseModel baseModel) {
        if (null != baseModel)
            attrs.putAll(baseModel.getAttrs());
    }

    public String getStr(String key) {
        Object value = attrs.get(key);
        if (null == value)
            return null;
        if (value instanceof String || value instanceof JSONObject)
            return value.toString();
        if (value instanceof JSONArray)
            return ((JSONArray) value).toJSONString();
        return null;
    }

    public String getStr(String key, String defaultValue) {
        Object value = attrs.get(key);
        if (null == value)
            return null;
        if (value instanceof String || value instanceof JSONObject)
            return value.toString();
        if (value instanceof JSONArray)
            return ((JSONArray) value).toJSONString();
        return defaultValue;
    }

    public int getInt(String status) {
        Object value = attrs.get("status");
        if (null == value || !(value instanceof Integer))
            return -1;
        return (int) value;
    }

    public int getInt(String status, int defaultValue) {
        Object value = attrs.get("status");
        if (null == value || !(value instanceof Integer))
            return defaultValue;
        return (int) value;
    }

    public Map getAttrs() {
        return attrs;
    }

//    /**
//     * 获取初始化的params jsonObject其余的属性已经加入。
//     *
//     * @param t
//     * @return
//     */
//    public RequestParams getParams(T t) {
//        RequestParams params = new RequestParams();
////        if (StringUtil.isNotEmpty(UserService.getInstance().getUser().getId()))
////            params.addBodyParameter("user_id", UserService.getInstance().getUser().getId());
////        if (StringUtil.isNotEmpty(UserService.getInstance().getUser().getToken()))
////            params.addBodyParameter("token", UserService.getInstance().getUser().getToken());
//        params.addHeader("Content-Type", "application/json");
//        String json = JSON.toJSONString(t);
//        try {
//            params.setBodyEntity(new StringEntity(json, "UTF-8"));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        Log.d(t.getClass().getName(), "json=" + json);
//        return params;
//    }
}